package com.oss.mq.service.impl;

import com.oss.mq.entity.pojo.ServiceMonitor;
import com.oss.mq.mapper.ServiceMonitorMapper;
import com.oss.mq.mapper.ServiceRegisterMapper;
import com.oss.mq.entity.pojo.ServiceRegister;
import com.oss.mq.service.IServiceRegisterService;
import com.oss.mq.utils.MessageUtils;
import com.oss.mq.utils.SnowflakeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.OperatingSystemMXBean;
import java.util.Date;
import java.util.List;

/**
 * Author yaoyaoyao
 * Date 2024/7/17 15:23
 */
@Service
public class ServiceRegisterServiceImpl implements IServiceRegisterService {
    @Resource
    ServiceRegisterMapper registerMapper;
    @Resource
    ServiceMonitorMapper monitorMapper;
    @Autowired
    MessageUtils messageUtils;
    @Override
    public Integer addRegister(ServiceRegister register) {
        Long serviceId = SnowflakeUtils.generate();
        register.setIsValid("Y").setCreateUser(1).setCreateDate(new Date())
                .setModifyUser(1).setModifyDate(new Date())
                .setServiceId(serviceId);
        String ip = register.getIp();

        //建立连接
        // 获取操作系统管理接口
        OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
        // 获取CPU数量
        int cpuCount = osBean.getAvailableProcessors();
        // 获取内存管理接口
        MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
        // 获取堆内存使用情况
        MemoryUsage heapMemoryUsage = memoryBean.getHeapMemoryUsage();
        int memory = (int) (heapMemoryUsage.getMax()/(1024 * 1024 * 1024));
        register.setCpu(cpuCount).setMemory(memory).setLateMonitorTime(new Date())
                .setServiceState("0");

        //设置监控器
        ServiceMonitor monitor = new ServiceMonitor();
        osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
        if (osBean == null) {
            // 如果无法获取OperatingSystemMXBean实例，则使用标准的OperatingSystemMXBean
            osBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        }
        double cpuUsageDouble = osBean.getSystemLoadAverage();
        int cpuUsage = (int)cpuUsageDouble * 100;
        int memoryUsage = (int) (heapMemoryUsage.getUsed()/(1024 * 1024 * 1024));
        monitor.setServiceId(serviceId);
        monitor.setMonitorId(SnowflakeUtils.generate()).setCreateDate(new Date())
                .setIsValid("Y").setCreateUser(1).setModifyUser(1)
                .setModifyDate(new Date()).setCpuUsage(cpuUsage).setMemoryUsage(memoryUsage);
        monitorMapper.insertSelective(monitor);

        return registerMapper.insertSelective(register);
    }

    @Override
    public void deleteRegister(Long id) {
        registerMapper.deleteByPrimaryKey(id);
        monitorMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void modifyRegister(ServiceRegister register) {
        register.setModifyDate(new Date()).setModifyUser(1);
        registerMapper.updateByPrimaryKeySelective(register);
    }

    @Override
    public List<ServiceRegister> selectRegister() {
        return null;
    }

    //执行任务
    public void execute(ServiceRegister register) {

        try {
            Thread.sleep(6000);
        } catch (InterruptedException e) {
            messageUtils.hostSendMessage(register.getIp(), (byte) 3,"task failed");
            return;
        }
        messageUtils.hostSendMessage(register.getIp(), (byte) 3,"task success");
    }

    //心跳
    public void heartBeat(){
        //System.out.println(this.ip+" heart_beat"+new Date().getTime());
        List<ServiceRegister> registers = registerMapper.selectAllLive();
        if (registers.size()!=0){
            for (ServiceRegister register:registers){
                messageUtils.hostSendMessage(register.getIp(), (byte) 1,"heart_beat");
            }
        }
    }
}
